import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { useSearchAPI } from "@/services/search";

export const useSearchStore = defineStore("search", () => {
  const searchKeyword = ref("");
  const searchResults = ref<any>(null);

  const songs = computed(() => {
    if (!searchResults.value?.items?.[0]) return [];
    return searchResults.value.items[0].musicListVoList.map((item: any) => ({
      id: item.music.musicId,
      name: item.music.musicName,
      artist: item.music.musicAuthor,
      typeId: item.music.musicTypeId,
      url: item.music.musicUrl,
      cover: item.music.musicCoverUrl,
      length: item.music.musicLength,
      status: item.music.status,
      score: item.music.musicAverageScore,
      lyric: item.music.lyric,
      isFavorite: item.favorStatus,
    }));
  });

  const artists = computed(() => {
    if (!searchResults.value?.items?.[0]) return [];
    return (
      searchResults.value.items[0].userInfoList?.filter(
        (user: any) => user.isSinger === 1
      ) || []
    );
  });

  const playlists = computed(() => {
    if (!searchResults.value?.items?.[0]) return [];
    return searchResults.value.items[0].playlist || [];
  });

  const { searchByKeyword } = useSearchAPI();

  function setSearchResults(results: any) {
    searchResults.value = results;
  }

  function setSearchKeyword(keyword: string) {
    searchKeyword.value = keyword;
  }

  async function search(keyword: string, type: string, uid: string) {
    setSearchKeyword(keyword);
    const result = await searchByKeyword(keyword, type, uid, 1, 20);
    setSearchResults(result.data);
  }

  return {
    searchKeyword,
    searchResults,
    songs,
    artists,
    playlists,
    setSearchResults,
    setSearchKeyword,
    search,
  };
});
